package com.useeinfo.oa.modules.base.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.dao.FacilityCatDao;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/5 10:45
 * @Description: 设备类型service
 */
@Service
public class FacilityCatBiz extends CrudBiz<FacilityCatDao, FacilityCat> {

    public Boolean existFacilityCatName(FacilityCat facilityCat,List<String> selectParentIds, Long enterpriseId) {
        if (StringUtils.isBlank(facilityCat.getCatName())) {
            return true;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("catName", facilityCat.getCatName());
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");

        // 当前分类的根节点（专业）
        if (CollectionUtils.isNotEmpty(selectParentIds)){
            FacilityCat rootCat = this.findRootCat(StringConverters.ToLong(selectParentIds.get(0)));
            if(rootCat != null){
                queryParam.getSqlMap().put("rootCatId", rootCat.getId()+"");
            }
        } else {
            queryParam.getSqlMap().put("nullParentId", "nullParentId");
        }

        List<FacilityCat> facilityCatList = findList(queryParam);

        if (facilityCat.getId() == null) {
            return CollectionUtils.isNotEmpty(facilityCatList);
        } else {
            return !((facilityCatList.size() == 1 && facilityCatList.get(0).getId().equals(facilityCat.getId())) || facilityCatList.size() == 0);
        }
    }

    /**
     * 根据名称判断是否有该设备分类(有返回 没有返回NULL)
     *
     * @param enterpriseId
     * @return
     */
    public FacilityCat getFacilityCatByName(String catName,String enterpriseId) {
        if(StringUtils.isBlank(catName)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("catName", catName);
        List<FacilityCat> facilityCatList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityCatList)){
            return facilityCatList.get(0);
        }
        return null;
    }

    /**
     * 根据名称模糊查询专业，判断是否有下属设备分类(有返回所有下属分类id， 没有返回空)
     *
     * @param enterpriseId
     * @return
     */
    public String getFacilityCatIdsByNameLike(String rootCatName,String enterpriseId) {
        if(StringUtils.isBlank(rootCatName)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        String ids = "";
        List<Long> idList = new ArrayList<>();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId);
        queryParam.getSqlMap().put("rootCatName", rootCatName);
        List<FacilityCat> facilityCatList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityCatList)){
            for(FacilityCat facilityCat : facilityCatList){
                List<Long> list = getChildrenCatIdList(facilityCat.getId());
                idList.addAll(list);
            }
            if (CollectionUtils.isNotEmpty(idList)) {
                for (int i = 0; i < idList.size(); i++) {
                    Long id = idList.get(i);
                    if (id != null && id > 0) {
                        ids += id;
                        if (i < idList.size() - 1) {
                            ids += ",";
                        }
                    }
                }
            }
        }

        return ids;
    }


    /**
     * 查询该设备类型有没有子设备（查询有没有儿子）
     * @param parentCatId
     * @return
     */
    public Boolean existHaveSon(Long parentCatId) {
        FacilityCat facilityCat = this.findModel(parentCatId);
        if(facilityCat==null){
            return false;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("parentId",parentCatId+"");
        List<FacilityCat> facilityCatList = this.findList(queryParam);
        return CollectionUtils.isNotEmpty(facilityCatList);
    }

    /**
     * 查询根上级(最上级)
     * @param catId
     * @return
     */
    public FacilityCat findRootCat(Long catId) {
        FacilityCat facilityCat = this.findModel(catId);
        if(facilityCat==null){
            return null;
        }
        if(facilityCat.getLvl()==0){
            return facilityCat;
        }
        String[] parentIds = facilityCat.getParentIds().split(",");
        return this.findModel(StringConverters.ToLong(parentIds[0]));
    }

    /**
     * 查询直属下级
     * @param parentCatId
     * @return
     */
    public List<FacilityCat> findSonList(Long parentCatId) {
        List<FacilityCat> facilityCatList = new ArrayList<>();
        if(parentCatId==null||parentCatId<1L){
            return facilityCatList;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("parentId",parentCatId+"");
        facilityCatList = this.findList(queryParam);
        return  facilityCatList;
    }

    /**
     * 递归变更
     * @param parentCatId
     * @return
     */
    public void recursionChangeParentIds(Long parentCatId) {
        FacilityCat parentCat = this.findModel(parentCatId);
        if(parentCat!=null){
            List<FacilityCat> list = findSonList(parentCatId);
            if(CollectionUtils.isNotEmpty(list)){
                for (FacilityCat sonCat:list){
                    sonCat.setLvl((parentCat.getLvl()!=null?parentCat.getLvl():0)+1);
                    sonCat.setParentIds((StringUtils.isEmpty(parentCat.getParentIds())?"":(parentCat.getParentIds()+","))+parentCat.getId());
                    this.addOrUpdate(sonCat);
                    recursionChangeParentIds(sonCat.getId());
                }
            }
        }
    }


    /**
     * 根据父节点ID查询所有子孙节点ID（不包括父节点ID）List格式
     * @param parentCatId 父节点ID
     * @return
     */
    public List<Long> getChildrenCatIdList(Long parentCatId){
        List<Long> result = new ArrayList<>();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("parentId",parentCatId+"");
        List<FacilityCat> facilityCatList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityCatList)){
            for(FacilityCat facilityCat : facilityCatList){
                result.add(facilityCat.getId());
                List<Long> list = getChildrenCatIdList(facilityCat.getId());
                result.addAll(list);
            }
        }
        return result;
    }


    /**
     * 根据父节点ID查询所有子孙节点ID（不包括父节点ID） String格式
     * @param parentCatId 父节点ID
     * @return
     */
    public String getChildrenCatIds(Long parentCatId){
        String ids = "";
        List<Long> idList = getChildrenCatIdList(parentCatId);
        if(CollectionUtils.isNotEmpty(idList)){
            for (int i = 0; i < idList.size(); i++) {
                Long id = idList.get(i);
                if(id!=null&&id>0){
                    ids+=id;
                    if(i<idList.size()-1){
                        ids+=",";
                    }
                }
            }
        }
        return ids;
    }


    /**
     * 查询区域完全树形json
     * @param parentId
     * @return
     */
    public JSONArray findTreeData(Long parentId, Long enterpriseId) {
        JSONArray result = new JSONArray();
        QueryParam queryParam = new QueryParam();
        if(enterpriseId!=null){
            queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        }
        if(parentId!=null){
            queryParam.getSqlMap().put("parentId", parentId+"");
        }else{
            queryParam.getSqlMap().put("lvl", "1");
        }
        List<FacilityCat> facilityCatList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityCatList)){
            for (FacilityCat facilityCat:facilityCatList){
                JSONObject json = new JSONObject();
                json.put("id",facilityCat.getId());
                json.put("facilityCatName",StringConverters.null2String(facilityCat.getCatName()));
                result.add(json);
            }
        }
        return findChildrenTreeData(result);
    }

    /**
     * 递归查询下级json
     * @param array
     * @return
     */
    public JSONArray findChildrenTreeData(JSONArray array) {
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            JSONArray childrenArray = new JSONArray();
            json.put("childrenArray",childrenArray);
            json.put("childrenCount",0);
            Long parentId = json.getLong("id");
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("parentId", parentId+"");
            List<FacilityCat> facilityCatList = this.findList(queryParam);
            if(CollectionUtils.isNotEmpty(facilityCatList)){
                for (FacilityCat facilityCat:facilityCatList){
                    JSONObject childrenJson = new JSONObject();
                    childrenJson.put("id",facilityCat.getId());
                    childrenJson.put("facilityCatName",StringConverters.null2String(facilityCat.getCatName()));
                    childrenArray.add(childrenJson);
                }
                findChildrenTreeData(childrenArray);
                json.put("childrenArray",childrenArray);
                json.put("childrenCount",childrenArray.size());
            }
        }
        return array;
    }

}
